<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 幕小铺科技（大连）有限公司 [ http://www.XXX.com ]
// +----------------------------------------------------------------------
// | 2020/06/10
// +----------------------------------------------------------------------
namespace app\erp\logic;
use app\erp\model\ErpAllocation;
use think\facade\Hook;
use think\DB;
use util\Tree;
use think\facade\Debug;
use think\facade\Cache;
/**
 * 调拨管理-入库
 * @package app\erp\model
 */
class AllocationWarehousinglogic{

    /**
     * 首页
     * @author  dou<51779987@qq.com>
     * @return array_out(code, message, data)
     */
    public function index($user_id, $code, $from_warehouse_id, $to_warehouse_id, $handled_by,$all_status='2'){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
                'user_id' => $user_id,
            ];
            /********行为参数赋值（*）********/

            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
            $map = [];//搜索处理
            if($user_id != '')          $map[] = ['uid', 'like', '%'. $user_id .'%'];
            if($from_warehouse_id > 0) 	$map[] = ['from_warehouse_id', '=', $from_warehouse_id];
            if($to_warehouse_id > 0) 	$map[] = ['to_warehouse_id', '=', $to_warehouse_id];
            if($code != '') 			$map[] = ['code', 'like', '%'. $code .'%'];
            if($handled_by != '') 		$map[] = ['handled_by', 'like', '%'. $handled_by .'%'];
            if($all_status != '') 		$map[] = ['all_status', '=', $all_status];
            $list =  model('ErpAllocation', 'model') -> where($map) -> order('create_time desc') -> paginate();//获取列表
            $rel_list = [];
            foreach($list as $key => $value){
                $rel_list[$key]['uid'] 			        = (int)$value['uid'];
                $rel_list[$key]['fromWarehouseId']      = (string)$value['from_warehouse_id'];
                $rel_list[$key]['fromWarehouseIdNick']  = (string)get_nick_name('1','ErpWarehouse','id',$value['from_warehouse_id'],'title');
                $rel_list[$key]['toWarehouseId'] 	    = (string)$value['to_warehouse_id'];
                $rel_list[$key]['toWarehouseIdNick'] 	= (string)get_nick_name('1','ErpWarehouse','id',$value['to_warehouse_id'],'title');
                $rel_list[$key]['remark'] 		        = (string)$value['remark'];
                $rel_list[$key]['code'] 		        = (string)$value['code'];
                $rel_list[$key]['handledBy']            = (string)$value['handled_by'];
                $rel_list[$key]['createTime']           = (string)$value['create_time'];
                $rel_list[$key]['updateTime']           = (string)$value['update_time'];
                //查询sku表
                $sku = model('ErpAllocationSku') -> where(['allocation_id'=>$value['id']])->select()->toArray();
                $rel_list[$key]['sku']['id']                = $sku[0]['id'];
                $rel_list[$key]['sku']['allocationId']      = $sku[0]['allocation_id'];
                $rel_list[$key]['sku']['skuId']             = $sku[0]['sku_id'];
                $rel_list[$key]['sku']['num']               = $sku[0]['num'];
                $rel_list[$key]['sku']['createTime']        = $sku[0]['create_time'];
                $rel_list[$key]['sku']['createTime']        = $sku[0]['create_time'];
            }
            $result_list = [];
            $result_list['total']  			= (int)$list -> total();//总数
            $result_list['current_page']	= (int)$list -> currentPage();//页码
            $result_list['last_page']   	= (int)$list -> lastPage();//总页数
            $result_list['per_page']   		= (int)$list -> listRows();//每页条数
            $result_list['data'] 			= $rel_list;
            /********业务逻辑********/

            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
            DB::commit();
            return array_out(200, 'success', $result_list);
            /********逻辑返回********/

        } catch (\Exception $e) {
            DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }


    /**
     * 入库操作按钮
     * @author dou<51779987@qq.com>
     * @return array_out(code, message, data)
     */
    public function warehousing($user_id,$id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
                'user_id' 	        => $user_id,
                'id'                => $id,
            ];
            /********行为参数赋值（*）********/

            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
            //更新allocation调拨状态 0申请中 1已审核 2已出库 3取消出库 4已入库
            $rel = model('ErpAllocation') -> editDataOutGoing($id,'4');
            if($rel['code'] == 200){
                $rel = model('ErpAllocation') -> warehousing($id);//入库加库存
                if($rel['code'] < 0){
                    DB::rollback();
                    return array_out(-1003, $rel['message']);//后置错误 -1003
                }
            }else{
                DB::rollback();
                return array_out(-1005, 'error');//添加失败 返回-1005,error
            }
            /********业务逻辑********/

            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
            DB::commit();
            return array_out(200, 'success',$rel['data']);
            /********逻辑返回********/

        } catch (\Exception $e) {
            DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

}